package main

import (
	"fmt"
	"time"
)

func main() {
	now := time.Now()
	// 时间
	fmt.Println(now)          // 2022-08-31 20:18:43.5106426 +0800 CST m=+0.002307601
	fmt.Println(now.Date())   // 2022 August 31
	fmt.Println(now.Year())   // 2022
	fmt.Println(now.Month())  // August
	fmt.Println(now.Day())    // 31
	fmt.Println(now.Hour())   // 20
	fmt.Println(now.Minute()) // 18
	fmt.Println(now.Second()) // 43

	// 时间戳
	fmt.Println(now.Unix())     // 1661948636
	fmt.Println(now.UnixNano()) // 1661948636252633600

	// 时间戳转日期
	ret := time.Unix(1661948636, 0)
	fmt.Println(ret)         // 2022-08-31 20:23:56 +0800 CST
	fmt.Println(ret.Year())  // 2022
	fmt.Println(ret.Month()) // August
	fmt.Println(ret.Day())   // 31

	// 时间间隔
	fmt.Println(time.Second) // 1s

	// now当前时间 + 24小时
	fmt.Println(now.Add(24 * time.Hour)) // 2022-09-01 20:30:29.537553 +0800 CST m=+86400.002315601

	// 定时器
	//timer := time.Tick(time.Second)
	//for t := range timer {
	//	// 1秒执行一次
	//	fmt.Println(t)
	//}

	// 时间格式化
	fmt.Println(now.Format("2006-01-02"))              // 2022-08-31
	fmt.Println(now.Format("2006/01/02 15:04:05"))     // 2022/08/31 21:07:57
	fmt.Println(now.Format("2006/01/02 03:04:05 PM"))  // 2022/08/31 09:08:39 PM
	fmt.Println(now.Format("2006/01/02 15:04:05.000")) // 2022/08/31 21:09:10.569

	// 解析字符串类型的时间
	timeObj, err := time.Parse("2006-01-02", "2022-08-03")
	if err != nil {
		fmt.Printf("parse time failed, err:%v\n", err)
		return
	}
	fmt.Println(timeObj)        // 2000-08-03 00:00:00 +0000 UTC
	fmt.Println(timeObj.Unix()) // 965260800

	// 两个时间相减
	nextYear, err2 := time.Parse("2006-01-02", "2022-08-31")
	if err2 != nil {
		fmt.Printf("parse time failed, err:%v\n", err2)
		return
	}
	d := nextYear.Sub(now)
	fmt.Println(d)

	// sleep
	//n := 5
	//fmt.Println("开始sleep")
	//time.Sleep(time.Duration(n) * time.Second)
	//fmt.Println("5秒钟过去了")

	// 按东八区的时区格式解析字符串格式的时间
	loc, err3 := time.LoadLocation("Asia/Shanghai")
	if err3 != nil {
		fmt.Println("load loc failed, err:%v\n", err3)
		return
	}
	// 按照指定时区解析时间
	timeObj, err4 := time.ParseInLocation("2006-01-02 15:04:05", "2022-09-01 21:25:51", loc)
	if err4 != nil {
		fmt.Printf("parse time failed, err:%v\n", err4)
		return
	}
	fmt.Println(timeObj) // 2022-09-01 21:25:51 +0800 CST
	// 时间对象相减
	td := timeObj.Sub(now)
	fmt.Println(td)		// 23h40m27.0372446s
}
